<?php

namespace App\Http\Controllers\Adminer;

use App\Exceptions\BaseException;
use App\Models\Purview;
use App\Http\Controllers\AdminController;
use App\Services\PurviewService;
use App\Services\TreeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class PurviewController extends AdminController
{
    protected $data;
    function __construct()
    {
        parent::__construct();
        //dd($this->base);
        //dd(request()->route()->getAction());
        $this->data['title'] = $this->base['controller'].$this->base['action'];
        $this->data['title_en'] = "Authority";
        $this->data['title_url'] = route("purview.index");
        $this->data['is_search'] = FALSE;
        //return view("adminer.index.index",$data);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //dd($this->data);
        $purviewarr = PurviewService::purviewAllByOpt();
        $purviewarr = $purviewarr->toArray();
        $status_names = Purview::$status_names;
        $html = "";
        if(!empty($purviewarr)){
            foreach($purviewarr as $key=>$view){
                $purviewarr[$key]['status_name'] = $status_names[$view['status']];
                $purviewarr[$key]['json_data'] = json_encode($view);
            }
            $html .= (new TreeService())->getList($purviewarr);
        }
        $this->data['html'] = $html;
        return view("adminer.purview.index",$this->data);
    }

    public function sort(Request $request){
        $data = $request->post('data');
        $sorts = json_decode($data,true);
        if(is_array($sorts)){
            //dd($sorts);
            $this->_sort(0,$sorts);
        }else{
            throw new BaseException('数据出错');
        }
    }
    private function _sort($parent,$children){
        foreach($children as $c=>$child){
            $lft = $c;
            $new_parent = $child['id'] ?? 0;
            if($new_parent == 0){
                return false;
            }
            // 执行修改
            $payload['lft'] = $lft;
            $payload['parent'] = $parent;
            Purview::where('id',$new_parent)->update($payload);
            $new_chilren = $child['children'] ?? [];
            if(count($new_chilren) > 0){
                $this->_sort($new_parent,$new_chilren);
            }
        }
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $purviewarr = PurviewService::purviewAllByOpt();
        $purviewarr = $purviewarr->toArray();
        $status_names = Purview::$status_names;
        $html = "";
        if(!empty($purviewarr)){
            $html .= (new TreeService())->getList($purviewarr,FALSE);
        }
        $this->data['opt_html'] = $html;
        return view("adminer.purview.create",$this->data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $info=$request->only(['status', 'parent','pid','title','func','url','f_main','icon']);
        // 验证不为空
        Validator::make($info, [
            'title' => ['bail','required',Rule::unique('purview'),],
        ],[
            'title.required'       => '请输入权限名称',
            'title.unique'         => '权限名称已使用',
        ])->validate();
        $last = PurviewService::getLastByParent($info['parent']);
        if(!$last){
            $info['lft'] = $info['parent'];
        }else{
            $info['lft'] = $last->id;
        }
        $data = new Purview($info);
        if(!$data->save()){
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"新增权限失败");
            throw new BaseException('保存失败');
        }
        AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"新增权限-".$info['title']);
        return $this->successResponse('保存成功',[],200,route("purview.index"));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Purview  $purview
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $info = Purview::find($id);
        if(!$info){
            throw new BaseException('数据不存在');
        }else{
            return $this->successResponse('',$info->toArray(),200,'');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Purview  $purview
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $purviewarr = PurviewService::purviewAllByOpt();
        $purviewarr = $purviewarr->toArray();
        $status_names = Purview::$status_names;
        $html = "";
        if(!empty($purviewarr)){
            $html .= (new TreeService())->getList($purviewarr,FALSE);
        }
        $this->data['opt_html'] = $html;
        $info = Purview::find($id);
        $this->data['curr_html'] = '';
        if($info->parent != 0){
            $parent = Purview::find($info->parent);
            $this->data['curr_html'] = '<option value="'.$parent->id.'">'.$parent->title.'</option>';
        }

        $this->data['info'] = $info;
        return view("adminer.purview.edit",$this->data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Purview  $purview
     * @return \Illuminate\Http\Response
     */
    public function update($id,Request $request)
    {
        $info = Purview::find($id);
        if($info){
            $payload=$request->only(['status', 'parent','pid','title','func','url','f_main','icon']);
            // 验证不为空
            Validator::make($payload, [
                'title' => ['bail','required',Rule::unique('purview')->ignore($id),],
            ],[
                'title.required'       => '请输入权限名称',
                'title.unique'         => '权限名称已使用',
            ])->validate();
            $payload['f_main'] = $payload['f_main'] ?? 0;
            if(!Purview::where('id',$id)->update($payload)){
                AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"新增权限失败");
                throw new BaseException('保存失败');
            }
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"新增权限-".$payload['title']);
            return $this->successResponse('保存成功',[],200,route("purview.index"));
        }else{
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],$id,"数据错误");
            return response()->json([
                'code'      => 422001,
                'message'   => "数据错误",
            ]);
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Purview  $purview
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // 如果有下级,无法删除
        if(Purview::where('parent',$id)->count() > 0){
            throw new BaseException('请先删除子权限');
        }
        if(!Purview::destroy($id)){
            throw new BaseException('操作失败');
        }

        return $this->successResponse('操作成功');
    }
}
